package logic

import (
	"context"
	"fmt"
	"hui-hui/hui_hui_rpc/hui_hui_rpc"
	"hui-hui/hui_hui_rpc/internal/svc"
	"hui-hui/models"
	"math/rand"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type SmsCaptchaLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSmsCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SmsCaptchaLogic {
	return &SmsCaptchaLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SmsCaptchaLogic) SmsCaptcha(in *hui_hui_rpc.SmsCaptchaRequest) (*hui_hui_rpc.SmsCaptchaResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("%s:%s", in.From, in.Phone)
	get, _ := models.RDB.Get(models.Ctx, key+"count").Result()
	if get != "" {
		return nil, fmt.Errorf("一分钟内只得发送一条短信")
	}
	code := fmt.Sprintf("%d", rand.Intn(9000)+1000)

	//captcha, err := pkg.SmsCaptcha(in.Phone, code)
	//if err != nil {
	//	return nil, err
	//}
	//if *captcha.Body.Code != "OK" {
	//	return nil, fmt.Errorf(*captcha.Body.Message)
	//}

	models.RDB.Set(models.Ctx, key, code, 3*time.Minute)
	models.RDB.Set(models.Ctx, key+"count", code, 1*time.Minute)
	return &hui_hui_rpc.SmsCaptchaResponse{}, nil
}
